<?php

namespace common\jobs;

use Yii;
use yii\console\Exception;
use common\helpers\ArrayHelper;
use common\models\ofc\OfcMatch;

/**
 * 评论之后执行队列任务
 * Class AfterMatchJob.
 */
class AfterMatchJob extends BaseRetryableJob {

    public $season_id = 0;
    public $teams = [];
    public $matchs = [];

    /**
     * @param \yii\queue\Queue $queue which pushed and is handling the job
     */
    public function execute($queue) {
        if (!$this->season_id || empty($this->teams) || empty($this->matchs)) {
            throw new Exception('AfterMatchJob reqire params...');
        }

        $teams = $this->teams;
        $matchs = $this->matchs;

        Yii::error([
            $matchs
        ], __CLASS__);

        foreach ($matchs as $item) {
            $match = OfcMatch::findOrNew([
                'channel_id' => ArrayHelper::getValue($item, 'id'),
            ]);
            $chostid = ArrayHelper::getValue($item, 'home_team_id');
            $cguestid = ArrayHelper::getValue($item, 'away_team_id');

            $hostTeam = ArrayHelper::getValue($teams, $chostid);
            $guestTeam = ArrayHelper::getValue($teams, $cguestid);

            $match->attributes = [
                'host_team_id' => $hostTeam ? $hostTeam->id : 0,
                'guest_team_id' => $guestTeam ? $guestTeam->id : 0,
                'host_score' => ArrayHelper::getValue($item, 'home_scores.0', 0),
                'guest_score' => ArrayHelper::getValue($item, 'away_scores.0', 0),
                'match_time' => ArrayHelper::getValue($item, 'match_time', 0),
                'season_id' => $this->season_id,
//                'venue_id' => $hostTeam ? $hostTeam->venue_id : 0,
                'group_id' => ArrayHelper::getValue($item, 'round.group_num', 0),
                'round_id' => ArrayHelper::getValue($item, 'round.round_num', 0),
                'match_status' => ArrayHelper::getValue($item, 'status_id', 0),
            ];
            if (!$match->save()) {
                Yii::error($match->errors, __METHOD__);
            }
        }
    }

}
